package hygprs

import (
	"fmt"
	"runtime"
)

/*
恒宇GPRS协议
粘包处理和字段解析
*/

// 异常数据处理
var Debug func(msg string, data []byte)

/*
解析包内字段
*/
func ParseFields(data []byte) (m map[byte][]byte, other []byte) {
	m = make(map[byte][]byte)
	other = make([]byte, 0)
	defer func() {
		if info := recover(); info != nil {
			// 处理已知的错误，或者打印日志
			if data[6] == 0xaf || data[6] == 0xf3 {
				// 0xaf包没有校验和，正常返回
			} else {
				_, file, line, _ := runtime.Caller(-1)
				if Debug != nil {
					Debug(fmt.Sprint("解析数据错误 info:", info, " file:", file, " line:", line), data)
				}
			}
		}
	}()
	length := len(data)
	offset := PositionData
	for length+PositionChecksum > offset {
		b := data[offset]
		if _, ok := m[b]; ok {
			goto next
		}
		switch b {
		case LineID, BusID, OperatorID, Unix, 0x07, 0x08, 0x11, 0x13, 0x14, 0x15, 0x16, 0x17, 0x1b, 0x1e, 0x1f, 0x20, 0x21, 0x23,
			0x24, 0x27, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x40, 0x41, 0x42, 0x46, 0x47, 0x48, 0x49, 0x10:
			if length > offset+4 {
				m[b] = data[offset+1 : offset+5]
				offset += 5
			}
		case 0x03, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x18, 0x1a, 0x1d, 0x22, 0x25, 0x26, 0x35, 0x38, 0x43, 0x44, 0x45, 0x4a, 0x4c, 0xef:
			if length > offset+1 {
				m[b] = data[offset+1 : offset+2]
				offset += 2
			}
		case 0x09, 0x0a, 0x19, 0x1c, 0x28, 0x29, 0x30, 0x39, 0x4b:
			if length > offset+2 {
				m[b] = data[offset+1 : offset+3]
				offset += 3
			}
		case 0x12, 0xf1, 0xf2:
			m[b] = data[offset+1 : length+PositionChecksum]
			offset = length + PositionChecksum
		default:
			goto next
		}
	}
next:
	other = data[offset : length+PositionChecksum]
	return
}

// 解析12字段中的数据
// 每一项开头是名称，然后是两个字节的长度，后面是相应长度的数据
func Parse0x12(data []byte) map[byte][]byte {
	var offset int
	var res = make(map[byte][]byte)
	for offset < len(data) {
		l := int(ToUint16(data[offset+1 : offset+3]))
		res[data[offset]] = data[offset+3 : offset+3+l]
		offset += l + 3
	}
	return res
}
